<template>
	<view>
		<view class="my-search-box">
			<uni-search-bar @input="input" :radius="100" cancelButton="none" placeholder="请输入搜索内容"></uni-search-bar>
		</view>
		<view class="search-list" v-if="searchResults.lenght !== 0 & searchkeyword.length !==0">
			<view class="search-item" v-for="(item,index) in searchResults" :key="index" @click="goToGoodsDetail(item)">
				<view class="goods-name">{{item.goods_name}}</view>
				<uni-icons type="forward" size="18" color="#333333"></uni-icons>
			</view>
		</view>
		<view class="history-box" v-else>
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash-filled" size="18" color="#717171" @click="delAllHistory"></uni-icons>
			</view>
			<view class="history-list">
				<view class="history-item" v-for="(item2,index2) in historyes" :key="index2">
					<uni-icons type="closeempty" size="12" color="#afafaf" @click="delSearchHistory(item2)"></uni-icons>
					<uni-tag :text="item2" :inverted="true" size="normal" @click="goToGoodsList(item2)" />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		onLoad() {
			let str = decodeURIComponent(uni.getStorageSync('searchkeyword') || [])
			this.searchHistoryList = JSON.parse(str)
			// this.searchHistoryList = JSON.parse(uni.getStorageSync('searchkeyword') || [])//存在隐患，第一次执行会报错，原因未知
		},
		data() {
			return {
				timer: null,
				searchkeyword: '',
				searchResults: [],
				searchHistoryList: []
			};
		},
		methods: {
			// 搜索逻辑
			async getSearchList() {
				if (this.searchkeyword === '') {
					// 当搜索内容为空时清空搜索列表
					this.searchResults = []
					return
				} else {
					const {
						data: res
					} = await uni.$http.get('/api/public/v1/goods/qsearch', {
						query: this.searchkeyword
					})
					if (res.meta.status !== 200) {
						uni.$showMsg()
					} else {
						this.searchResults = res.message
						console.log('2.搜索返回的数据结果', res.message);
						this.savesearchHistory()
					}
				}
			},
			// 定时器
			input(e) {
				clearTimeout(this.timer) //如果用户在1s内连续输入内容就清除之前的定时器
				this.timer = setTimeout(() => {
					console.log("1.搜索的内容", e);
					// 将输入的关键词赋值给变量
					this.searchkeyword = e
					this.getSearchList()
				}, 1000)
			},
			// 点击跳转到商品详情
			goToGoodsDetail(item) {
				console.log("3.商品信息", item.goods_id);
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
				})
			},

			// 保存搜索历史
			savesearchHistory() {
				// 此处使用push方法会出现新搜索记录出现在最后和出现同样的搜索记录的问题（可以使用set方法进行去重操作或使用unshift但此方法会出发重排性能消耗较大）
				// this.searchHistoryList.push(this.searchkeyword)，将searchHistoryList new成一个新对象，然后先删除关键词再添加最后将set对象转为数组
				let set = new Set(this.searchHistoryList)
				set.delete(this.searchkeyword)
				set.add(this.searchkeyword)
				this.searchHistoryList = Array.from(set)
				// 将搜索记录数组转为字符串并存储到本地永久存储，然后在页面初始化时获取存储好的数据并重新转换成数组（解决页面刷新记录丢失的问题）
				uni.setStorageSync('searchkeyword', JSON.stringify(this.searchHistoryList))
			},
			// 单个删除
			delSearchHistory(item2) {
				console.log('删除的元素', item2);
				if (this.searchHistoryList.length > 0) {
					let index = this.searchHistoryList.indexOf(item2)
					this.searchHistoryList.splice(index, 1)
					console.log(this.searchHistoryList.length, this.searchHistoryList);
					uni.setStorageSync('searchkeyword', JSON.stringify(this.searchHistoryList))
				}
			},
			// 全部删除
			delAllHistory() {
				this.searchHistoryList = []
				uni.setStorageSync('searchkeyword', '[]')
			},
			// 根据关键词跳转到列表
			goToGoodsList(kw) {
				uni.navigateTo({
					url: '/subpkg/goods_list/goods_list?query=' + kw
				})
			},
		},
		computed: {
			historyes() {
				// reverse将数组顺序反转
				return [...this.searchHistoryList].reverse()
			}
		}
	}
</script>

<style lang="scss">
	// 官方组件也可以直接在uni.css中改，在源码改也行但不建议
	.my-search-box {
		position: sticky;
		top: 0;
		z-index: 99;
		height: 50px;
		background-color: #ffd242;
	}

	.search-list {
		.search-item {
			display: flex;
			line-height: 60rpx;
			border-bottom: #ebebeb 1px solid;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 10px;

			.goods-name {
				margin-left: 10px;
				font-size: 12px;
				color: #333333;
				width: 98vw;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}

	.history-box {
		.history-title {
			padding: 0 10px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 14px;
			font-weight: 500;
			color: #717171;
			line-height: 70rpx;
		}

		.history-list {
			// border: #f4ea2a 1px solid;
			padding: 0 10px;
			padding-bottom: 10px;
			display: flex;
			flex-wrap: wrap;
			justify-content: start;

			.history-item {
				position: relative;
				margin-top: 10px;
				margin-left: 5px;

				.uni-icons {
					position: absolute;
					top: -8px;
					right: -3px;
				}

				.uni-tag {
					border-radius: 8px;
				}
			}

		}
	}
</style>
